//
//  UIImageView+SDWebImageSwizzling.m
//  SchoolHelper
//
//  Created by 任辰东 on 2025/7/18.
//  Copyright © 2025 JSY. All rights reserved.
//

#import "UIImageView+SDWebImageSwizzling.h"
#import <SDWebImage/SDWebImage.h>
#import <objc/runtime.h>

@implementation UIImageView (SDWebImageSwizzling)

+ (void)load {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        // 方法列表
        [self swizzleSelector:@selector(sd_setImageWithURL:)
               withSelector:@selector(my_sd_setImageWithURL:)];

        [self swizzleSelector:@selector(sd_setImageWithURL:placeholderImage:)
               withSelector:@selector(my_sd_setImageWithURL:placeholderImage:)];

        [self swizzleSelector:@selector(sd_setImageWithURL:placeholderImage:options:)
               withSelector:@selector(my_sd_setImageWithURL:placeholderImage:options:)];

        [self swizzleSelector:@selector(sd_setImageWithURL:placeholderImage:options:completed:)
               withSelector:@selector(my_sd_setImageWithURL:placeholderImage:options:completed:)];
    });
}

+ (void)swizzleSelector:(SEL)originalSelector withSelector:(SEL)swizzledSelector {
    Method originalMethod = class_getInstanceMethod(self, originalSelector);
    Method swizzledMethod = class_getInstanceMethod(self, swizzledSelector);
    if (originalMethod && swizzledMethod) {
        method_exchangeImplementations(originalMethod, swizzledMethod);
    }
}

#pragma mark - 替换后的方法实现

- (void)my_sd_setImageWithURL:(NSURL *)url {
    NSURL *newURL = [self handleURL:url];
    // 调用原始实现（实际是调用 sd_setImageWithURL:）
    [self my_sd_setImageWithURL:newURL];
}

- (void)my_sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder {
    NSURL *newURL = [self handleURL:url];
    [self my_sd_setImageWithURL:newURL placeholderImage:placeholder];
}

- (void)my_sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options {
    NSURL *newURL = [self handleURL:url];
    [self my_sd_setImageWithURL:newURL placeholderImage:placeholder options:options];
}

- (void)my_sd_setImageWithURL:(NSURL *)url
             placeholderImage:(UIImage *)placeholder
                      options:(SDWebImageOptions)options
                    completed:(SDExternalCompletionBlock)completedBlock {
    NSURL *newURL = [self handleURL:url];
    [self my_sd_setImageWithURL:newURL placeholderImage:placeholder options:options completed:completedBlock];
}

#pragma mark - 自定义处理逻辑（可改）

- (NSURL *)handleURL:(NSURL *)url {
    if (!url) return nil;

    NSString *urlStr = url.absoluteString;

    if (![urlStr hasPrefix:@"http"]) {
        urlStr = [NSString stringWithFormat:@"%@/%@",kImageBaseUrl,urlStr];
    }

    // 示例：拼接 CDN 参数
    // urlStr = [urlStr stringByAppendingString:@"?x-oss-process=image/resize,w_300"];

    return [NSURL URLWithString:urlStr];
}


@end
